package org.dreamland.application

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.dreamland.application.query.LoginRequest
import org.dreamland.infrastructure.security.GraphicCaptchaManager
import org.dreamland.infrastructure.security.UsernamePasswordCaptchaAuthenticationToken
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.context.SecurityContextRepository
import org.springframework.stereotype.Service

@Service
class AuthenticationService(
        private val authenticationManager: AuthenticationManager,
        private val securityContextRepository: SecurityContextRepository,
        private val graphicCaptchaManager: GraphicCaptchaManager
) {

    fun login(
            loginRequest: LoginRequest,
            httpRequest: HttpServletRequest,
            httpResponse: HttpServletResponse,
    ): String {

        // 执行基础认证
        val authToken = UsernamePasswordCaptchaAuthenticationToken(
                loginRequest.username,
                loginRequest.password,
                loginRequest.captcha
        )
        val authentication = authenticationManager.authenticate(authToken)
        val securityContext: SecurityContext = SecurityContextHolder.createEmptyContext();
        securityContext.authentication = authentication
        SecurityContextHolder.setContext(securityContext)

        httpRequest.session // 显式创建 Session
        securityContextRepository.saveContext(securityContext, httpRequest, httpResponse)
        return httpRequest.session.id
    }

fun captchaBase64Code(httpRequest: HttpServletRequest): String {
    val captchaKey = httpRequest.session.id
    return graphicCaptchaManager.captchaBase64Code(captchaKey)
}
}